package com.walter.common.interceptors;

import com.walter.common.utils.TraceIdUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import static com.walter.common.constants.CommonConstant.HEADER_TRACE_ID;

/**
 * @author Walter
 * @date 2025/1/22 下午12:43
 **/
@Slf4j
@Configuration
public class FeignTraceInterceptor implements RequestInterceptor {
    /**
     * @Description 拦截feign进行拦截，并在请求头添加，需要添加的header参数
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        try {
            log.info("---------FeignTraceInterceptor apply01------------");
            // 获取请求对象
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (servletRequestAttributes != null) {
                HttpServletRequest request = servletRequestAttributes.getRequest();
                // 获取当前请求的header，获取到jwt令牌
                if (request.getHeader("Authorization") != null) {
                    template.header("Authorization", request.getHeader("Authorization"));
                }
                String traceId = TraceIdUtil.getTraceId();
                template.header(HEADER_TRACE_ID, traceId);
                log.info("---------FeignTraceInterceptor apply02------------");
            }
        } catch (Exception e) {
            log.error("FeignTraceInterceptor error",e);
        }
    }
}
